package Http2;

import java.io.OutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.File;

/*
  HTTP Response = Status-Line
    *(( general-header | response-header | entity-header ) CRLF)
    CRLF
    [ message-body ]
    Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
*/

public class Response {

    private static final int BUFFER_SIZE = 1024;//定义一个常量
    Request request;
    OutputStream output;

    public Response(OutputStream output) {//构造方法
        this.output = output;
    }

    public void setRequest(Request request) {
        this.request = request;
    }

    public void sendStaticResource() throws IOException {//用来发送静态的资源,例如 HTML 文件，抛出异常
        byte[] bytes = new byte[BUFFER_SIZE];//定义byte类型数组
        FileInputStream fis = null;//FileInputStream主要用于读取文件,将文件信息读到内存中。
        try {
            //将web文件写入到OutputStream字节流中
            File file = new File(HttpServer.WEB_ROOT, request.getUri());
            if (file.exists())//测试此抽象路径名表示的文件或目录是否存在。
            {
                fis = new FileInputStream(file);//实例化对象
                //是指创建类型的对象后，自动调用类中的构造方法，来进行成员变量的初始化。
                int ch = fis.read(bytes, 0, BUFFER_SIZE);//定义一个变量存放读入的数据
                while (ch != -1) {
                    output.write(bytes, 0, ch);//输出
                    ch = fis.read(bytes, 0, BUFFER_SIZE);//再读入
                }
            } else {
                // file not found
                String errorMessage = "HTTP/1.1 404 File Not Found\r\n" + "Content-Type: text/html\r\n"
                        + "Content-Length: 23\r\n" + "\r\n" + "helloworld";
                output.write(errorMessage.getBytes());//输出字符串
            }
        } catch (Exception e) {
            // thrown if cannot instantiate a File object
            System.out.println(e.toString());
        } finally {
            if (fis != null)
                fis.close();//关闭
        }
    }
}
